package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.UserLoginBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/1/7 08:27
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
            4004,
            2,
            "Dws_04_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 读取数据源, 过滤出用户的登录记录
        SingleOutputStreamOperator<JSONObject> loginStream = filterLoginLog(stream);
        // 2. 数据封装到 pojo 中
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToPojo(loginStream);
        
        // 3.开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
        
        // 4. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
       return beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1,
                                                UserLoginBean value2) throws Exception {
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        return value1;
                    }
                },
                new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserLoginBean> elements,
                                        Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
    
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<UserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> loginStream) {
        return loginStream
            .keyBy(obj -> obj.getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastLoginDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    // 用户的当天的第一条登录记录, 把 uuCt =1L;
                    
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    Long uuCt = 0L;
                    Long backCt = 0L;
                    
                    String lastLoginDate = lastLoginDateState.value();
                    if (!today.equals(lastLoginDate)) {
                        // 今天第一次登录
                        uuCt = 1L;
                        lastLoginDateState.update(today);
                        
                        // 需要判断下这个用户是不是回流用户
                        // 用户需要曾经登录过, 才需要判断是否为回流
                        if (lastLoginDate != null) { // 曾经登录过
                            if ((ts - AtguiguUtil.dateToTs(lastLoginDate)) / 1000 / 60 / 60 / 24 > 7) {
                                backCt = 1L;
                            }
                        }
                    }
                    
                    if (uuCt == 1) {
                        out.collect(new UserLoginBean(
                            "", "",
                            backCt, uuCt,
                            ts
                        ));
                    }
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterLoginLog(DataStreamSource<String> stream) {
        /*
        登陆:
            自动登录
                last_page_id == null && uid=! null
            
            访问过程中, 用户手动登录
                a -> login -> a(other)(need)
                
                last_page_id==login && uid != null
         */
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(60))
            )
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getString("last_page_id");
                    String uid = value.getString("uid");
                    return (lastPageId == null || "login".equals(lastPageId)) && uid != null;
                }
            });
    }
}
/*
用户域用户登录各窗口汇总表

当日独立用户数
    定义一个状态: 存储这个用户最后一次登录日期
    
    每来一条数据, 判断这条数据的日期是否和状态一致:
        如果一致, 就不是这个用户的第一条记录 uv=0L
        如果不一致, 这个用户的的当天的第一条记录  uv=1L
            更新状态
   

统计七日回流用户数
    1 日  ....8日登陆
    
    上面的状态存储了最后一次登录日期, 今天 - 状态的日期 > 7 , 就是 7日回流用户
    


 */